package com.climaxi.core.data;

import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.FileNotFoundException;
import android.content.Context;
import com.climaxi.core.ClimaxiLog;

import android.util.Log;

public class JSONParser {

	static InputStream is = null;
	static JSONObject jObj = null;
	static String json = "";

	// constructor
	public JSONParser() {

	}

	public JSONObject getJSONFromUrl(String url) {
		Log.v("FLOW",url);
		// Making HTTP request
		try {
			// defaultHttpClient
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(url);

			HttpResponse httpResponse = httpClient.execute(httpPost);
			HttpEntity httpEntity = httpResponse.getEntity();
			is = httpEntity.getContent();			

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			json = sb.toString();
			Log.v("FLOW",url);
		} catch (Exception e) {
			Log.e("Buffer Error", "Error converting result " + e.toString());
		}
		Log.v("FLOW",json);
		// try parse the string to a JSON object
		try {
			jObj = new JSONObject(json);
		} catch (JSONException e) {
			Log.e("JSON Parser", "Error parsing data " + e.toString());
		}

		// return JSON String
		return jObj;

	}
	
	public JSONObject postDataObject(String url, List<NameValuePair> nameValuePairs) {
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        InputStream is = null;
        String json = "";
        JSONObject jObj = null;
        
        try {
			if(nameValuePairs != null)
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			else
			{
				List<NameValuePair> _nameValuePairs = new ArrayList<NameValuePair>(2);
				_nameValuePairs.add(new BasicNameValuePair("token", "4dsg4gu324shd"));
				httppost.setEntity(new UrlEncodedFormEntity(_nameValuePairs));
			}
			httppost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.94 Safari/537.36");
            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity httpEntity = response.getEntity();
            is = httpEntity.getContent();

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        	Log.e("CLIMAX", "ClientProtocolException " + e.toString());
        } catch (IOException e) {
            // TODO Auto-generated catch block
        	Log.e("CLIMAX", "IOException " + e.toString());
        }
        
        try 
		{
			BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			json = sb.toString();
		} 
		catch (Exception e) 
		{
			ClimaxiLog.Trace("Error converting result " + e.toString());
		}
        Log.v("FLOW",json);
        try {
			jObj = new JSONObject(json);
		} 
		catch (JSONException e) 
		{
			ClimaxiLog.Trace("Error parsing data " + e.toString());
		}
		
		return jObj;
    }
	
	public JSONArray postDataArray(String url, List<NameValuePair> nameValuePairs) {
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        InputStream is = null;
        String json = "";
        JSONArray jObj = null;
        
        try {
        	if(nameValuePairs != null)
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			else
			{
				List<NameValuePair> _nameValuePairs = new ArrayList<NameValuePair>(2);
				_nameValuePairs.add(new BasicNameValuePair("token", "4dsg4gu324shd"));
				httppost.setEntity(new UrlEncodedFormEntity(_nameValuePairs));
			}
        	httppost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.94 Safari/537.36");
            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity httpEntity = response.getEntity();
            is = httpEntity.getContent();

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
        
        try 
		{
			BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			json = sb.toString();
		} 
		catch (Exception e) 
		{
			ClimaxiLog.Trace("Error converting result " + e.toString());
		}
        Log.v("FLOW",json);
        try {
			jObj = new JSONArray(json);
		} 
		catch (JSONException e) 
		{
			
			ClimaxiLog.Trace("Error parsing data " + e.toString());
		}
		
		return jObj;
    }
	
	public boolean saveFile(Context context, String fileName, String content)
	{
		boolean status = false;
		
		try 
		{
		  // open myfilename.txt for writing
		  OutputStreamWriter out = new OutputStreamWriter(context.openFileOutput(fileName,Context.MODE_PRIVATE));
		  // write the contents on mySettings to the file
		  out.write(content);
		  // close the file
		  out.close();
		  status = true;
		  
		} 
		catch (java.io.IOException e) {}
		
		return status;
	}
	
	public String getFile(Context context, String fileName)
	{
		String ret = "";
        
        try {
            InputStream inputStream = context.openFileInput(fileName);
            
            if ( inputStream != null ) 
            {
            	InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            	BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            	String receiveString = "";
            	StringBuilder stringBuilder = new StringBuilder();
            	
            	while ( (receiveString = bufferedReader.readLine()) != null ) 
            	{
            		stringBuilder.append(receiveString);
            	}
            	
            	inputStream.close();
            	ret = stringBuilder.toString();
            }
        }
        catch (FileNotFoundException e) {
        	ClimaxiLog.Trace("File not found: " + e.toString());
		} catch (IOException e) {
			ClimaxiLog.Trace("Can not read file: " + e.toString());
		}

        return ret;
	}
}
